package com.blogs.service;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import android.content.Context;

import com.blogs.entity.AppConfig;
import com.blogs.entity.Feed;
import com.blogs.entity.MsgEntity;
import com.blogs.tools.GetTextFromWeb;
import com.blogs.tools.TbBlogLine;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class OffLineGetTimeLine {
	private TbBlogLine db;
	private String url=AppConfig.GETTIMELINE_URL;
	public OffLineGetTimeLine(Context context,String channel,int page)
	{
		try {
			channel=URLEncoder.encode(channel,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		url+="&page="+page+"&since_id=&max_id=&channelpath="+channel+"&t="+new Date().getTime();
		db=new TbBlogLine(context, channel);
	}
	public ArrayList<Feed> loadData()
	{
		String result=GetTextFromWeb.Get(this.url);
		if(result.equals(""))
		{
			if(db!=null)
			{
				db.DbClose();
			}
			return null;
		}
		GsonBuilder builder = new GsonBuilder();
		Gson gson = builder.create();
		MsgEntity<ArrayList<Object>> msg=null;
		try
		{
			msg=gson.fromJson(result,MsgEntity.class);
		}
		catch(Exception e)
		{
			if(db!=null)
			{
				db.DbClose();
			}
			return null;
		}
		if(msg.op.equals(""))
		{
			if(db!=null)
			{
				db.DbClose();
			}
			return null;
		}
		ArrayList<Feed> feeds=new ArrayList<Feed>();
		Iterator<Object> iterator = msg.data.iterator();
		while (iterator.hasNext()) 
		{
			Map<String, Object> objs = (Map<String, Object>) iterator.next();
			Feed feed = new Feed(objs);
			feeds.add(feed);
		}
		if(db!=null)
		{
			db.Insert(feeds);
			db.DbClose();
		}
		return feeds;
	}
}
